#!/bin/bash

HOSTS_FILE=/etc/hosts
HOSTS_BAKFILE=/etc/hosts_bak

# run num slave containers
num=$1

# the defaut node number is 3
if [ $# = 0 ]
then
	num=3
fi
	
# delete old master container and start new master container
sudo docker rm -f master &> /dev/null
echo "start master container..."
sudo docker run -d -t --dns 127.0.0.1 -P --name master -h master.yaolun.com -e SLAVES=$num -w /root yaolunlun/hadoop_master &> /dev/null

# get the IP address of master container
START_IP=$(sudo docker inspect --format="{{.NetworkSettings.IPAddress}}" master)

if [ -f $HOSTS_BAKFILE ]
then
    sudo cp $HOSTS_BAKFILE $HOSTS_FILE
else
    sudo cp $HOSTS_FILE $HOSTS_BAKFILE
fi
sudo chmod 777 $HOSTS_FILE
sudo echo "" >> $HOSTS_FILE
sudo echo "$START_IP    master.yaolun.com" >> $HOSTS_FILE
sudo chmod 644 $HOSTS_FILE

# delete old slave containers and start new slave containers
i=1
while [ $i -lt $num ]
do
	sudo docker rm -f slave$i &> /dev/null
	echo "start slave$i container..."
	sudo docker run -d -t --dns 127.0.0.1 -P --name slave$i -h slave$i.yaolun.com -e JOIN_IP=$START_IP yaolunlun/hadoop_slave &> /dev/null
	((i++))
done 

# create a new Bash session in the master container and enter the Bash
sudo docker exec -it master bash

exit 0

